package com.cat2bug.junit.demo.security;

import com.cat2bug.junit.demo.service.UserRepository;
import com.google.common.base.Strings;
import lombok.NonNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author: yuzhantao
 * @CreateTime: 2024-03-29 11:12
 * @Version: 1.0.0
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private UserRepository userRepository;

    private Map<String, String> tokenMap = new ConcurrentHashMap<>();

    protected String decodeTokenFromRequest(HttpServletRequest request) {
        return request.getHeader("cat2bug_token");
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, @NonNull FilterChain filterChain) throws ServletException, IOException {
        String token = decodeTokenFromRequest(request);
        if (Strings.isNullOrEmpty(token)==false
                && tokenMap.containsKey(token)
                && Objects.isNull(SecurityContextHolder.getContext().getAuthentication())) {
            String username = tokenMap.get(token);
            UserDetails userDetails = userRepository.getUserByName(username);

            // 权限信息
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
            authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            SecurityContextHolder.getContext().setAuthentication(authentication);
        }
        filterChain.doFilter(request, response);
    }
}
